import datetime
from .db import cursor, conn
from utils.print_message import print_message

def select_user_by_user_id(user_id):
    sql = """
    SELECT * FROM user_info WHERE user_id = %s
    """
    cursor.execute(sql, (user_id,))
    return cursor.fetchone()

def insert_user(user_class):
    data = user_class.json()
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    data['create_time'] = now
    data['update_time'] = now

    columns = ", ".join(data.keys())
    placeholders = ", ".join(["%s"] * len(data))
    sql = f"INSERT INTO user_info ({columns}) VALUES ({placeholders})"
    params = tuple(data.values())
    
    # complete_sql = cursor.mogrify(sql, params)  # 移除.decode('utf-8')
    # print_message(f"完整SQL:{complete_sql}")

    cursor.execute(sql, params)
    conn.commit()
    return cursor.rowcount

def update_user(user_class):
    data = user_class.json()

    # 假设用 user_id 作为更新条件，不会更新它本身
    user_id = data.pop('user_id')

    # 拼接字段=占位符，如 "name=%s, followers_count=%s, ..."
    set_clause = ", ".join([f'{k}=%s' for k in data.keys()])
    
    sql = f"UPDATE user_info SET {set_clause} WHERE user_id = %s"
    # 用元组params
    params = tuple(data.values()) + (user_id,)
    
    cursor.execute(sql, params)
    conn.commit()
    return cursor.rowcount
